package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.dto.TokenDto;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.HttpUtil;
import cn.itsource.ymcc.vo.LoginVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.client.HttpClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author zongchangjiang
 * @since 2023-03-27
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    //密码模式获取token的接口地址
    private static final String PASSWORD_MODE_TOKEN_URL = "http://localhost:10086/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=%s";

    @Override
    public List<Permission> selectSN(Long id) {
        return baseMapper.selectSN(id);
    }

    /**
     * 发送请求去干 密码模式  登录  的access_token
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginVo loginVo) {
        String username = loginVo.getUsername();
        //查询数据库
        Login login = baseMapper.selectOne(new QueryWrapper<Login>().eq("username", username));
        String passwordUrl = String.format(PASSWORD_MODE_TOKEN_URL,
                login.getClientId(),//如果是地三方 就要从配置文件里面读取出来
                login.getClientSecret(),//如果是地三方 就要从配置文件里面读取出来
                login.getUsername(),
                loginVo.getPassword());

        String s = HttpUtil.sendPost(passwordUrl, null);
        System.out.println(s);
        TokenDto tokenDto = JSON.parseObject(s, TokenDto.class);


        //4.封装HashMap
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", tokenDto.getAccessToken());
        map.put("refresh_token", tokenDto.getRefreshToken());
        //当前登录用户信息
        login.setPassword(null);
        map.put("currentUser", JSON.toJSONString(login));
        return map;
    }


}
